# Twi2G v0.01
# a gtalk robot for twitter based on Google App Engine
# http://code.google.com/p/twi2g/
import base64
import xml.dom.minidom
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import xmpp
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class Id(db.Model):
  content = db.StringProperty()

class Index(webapp.RequestHandler):
  def get(self):
    user = ''
    psw = ''
    to = ''
    query = db.GqlQuery("SELECT * FROM Id")
    if len(query.fetch(1)):
      since_id = query[0].content
      if xmpp.get_presence(to):
        result = self.get_tweet(user,psw,since_id)
        since_id = self.send_tweet(result,to)
	query[0].delete()
	id = Id()
	id.content = since_id
	id.put()
      else:
	query[0].delete()
    else:
      if xmpp.get_presence(to):
	self.response.out.write('ol')
	result = self.get_tweet(user,psw)
	since_id = self.send_tweet(result,to)
	id = Id()
	id.content = since_id
	id.put()
  def get_tweet(self,user,psw,since_id=''):
    authString = 'Basic '+base64.b64encode(user+':'+psw)
    if since_id:
      url = 'http://twitter.com/statuses/friends_timeline.xml?since_id='+since_id
    else:
      url = 'http://twitter.com/statuses/friends_timeline.xml'
    self.response.out.write(url)
    data = urlfetch.fetch(url=url, headers={'Authorization':authString})
    return data.content
  def send_tweet(self,string,to):
    dom = xml.dom.minidom.parseString(string)
    root = dom.documentElement
    id = ''
    message = ''
    for status in root.childNodes:
      for node in status.childNodes:
        if node.nodeName == 'user':
          for omg in node.childNodes:
            if omg.nodeName == 'screen_name':
              single_message = omg.childNodes[0].data.encode('gb18030')+':\n'+single_message
              message = message + single_message
        if node.nodeName == 'text':
          single_message = node.childNodes[0].data+'\n ---------------------------------' 
    if message:
      xmpp.send_message(to,message+'\n****************************')
    id = root.getElementsByTagName('id')[0].childNodes[0].data
    return id 

application = webapp.WSGIApplication([('/',Index)],debug=True)
def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

